OUTFILE=debug
OUTBIN=bin
OBJFILE=obj
ifneq ($(OUTFILE), $(wildcard $(OUTFILE)))
$(shell mkdir -p $(OUTFILE) $(OUTFILE)/$(OUTBIN) $(OUTFILE)/$(OBJFILE))
endif

DIR_SRC = ./src/mcuevent/fifo/ ./src/mcuevent/serial/ ./src/mcuevent/ ./src/event/ ./src/
DIR_LIB = ./lib/
IGNORE_LIST = ./src/test.c
DIR_OBJ = ./debug/obj/
DIR_BIN = ./debug/bin/
TARGET = eventhub
# CROSS = arm-linux-
CROSS = 
CC = ${CROSS}gcc
CXX = ${CROSS}g++
 
LDLIBS := -lpthread -lrt
DIR_INC := ${DIR_LIB} ${DIR_SRC}
CFLAGS := -g -std=c99 -Wall ${foreach n,${DIR_INC},-I${n}}
CXXFLAGS := -g -Wall ${foreach n,${DIR_INC},-I${n}}
CPPFLAGS :=
LDFLAGS := ${foreach n,${DIR_LIB},-L${n}} ${LDLIBS}
 
empty =
space =${empty} ${empty}
VPATH := ${subst ${space},:,${DIR_SRC}}:${DIR_OBJ}:${DIR_BIN}
vpath %.c ${subst ${space},:,${DIR_SRC}}
vpath %.cpp ${subst ${space},:,${DIR_SRC}}
vpath %.o ${DIR_OBJ}
vpath %.d ${DIR_OBJ}
 
CSRC_WITH_PATH := ${foreach n,${DIR_SRC},${wildcard ${n}*.c}}
CSRC_WITH_PATH := ${filter-out ${IGNORE_LIST},${CSRC_WITH_PATH}}
CSRC := ${notdir ${CSRC_WITH_PATH}}
COBJ_WITH_PATH := ${patsubst %.c,${DIR_OBJ}%.o,${CSRC}}
COBJ := ${notdir ${COBJ_WITH_PATH}}
CDEF_WITH_PATH = ${COBJ_WITH_PATH:.o=.d}
CDEF = ${COBJ:.o=.d}
 
CXXSRC_WITH_PATH := ${foreach n,${DIR_SRC},${wildcard ${n}*.cpp}}
CXXSRC_WITH_PATH := ${filter-out ${IGNORE_LIST},${CXXSRC_WITH_PATH}}
CXXSRC := ${notdir ${CXXSRC_WITH_PATH}}
CXXOBJ_WITH_PATH := ${patsubst %.cpp,${DIR_OBJ}%.o,${CXXSRC}}
CXXOBJ := ${notdir ${CXXOBJ_WITH_PATH}}
CXXDEF_WITH_PATH = ${CXXOBJ_WITH_PATH:.o=.d}
CXXDEF = ${CXXOBJ:.o=.d}
 
TARGET_WITH_PATH := ${DIR_BIN}${TARGET}
 
DIR_OBJ ?= ./debug/
TARGET_WITH_PATH ?= ./debug/bin/main.exe
 
.PHONY:all
all:${TARGET}
 
${TARGET}:${COBJ_WITH_PATH} ${CXXOBJ_WITH_PATH}
ifneq (${empty},${findstring .cpp,${CXXSRC}})
	${CXX} $^ -o ${DIR_BIN}$@ ${LDFLAGS}
else
	${CC} $^ -o ${DIR_BIN}$@ ${LDFLAGS}
endif
 
${COBJ_WITH_PATH}:${DIR_OBJ}%.o:%.c
	${CC} ${CFLAGS} -c -o $@ $<
${CXXOBJ_WITH_PATH}:${DIR_OBJ}%.o:%.cpp
	${CXX} ${CXXFLAGS} -c -o $@ $<
${CDEF_WITH_PATH}:${DIR_OBJ}%.d:%.c
	${CC} ${CFLAGS} -MM -MT "${subst .d,.o,$@} $@" -MF "$@" $<
${CXXDEF_WITH_PATH}:${DIR_OBJ}%.d:%.cpp
	${CXX} ${CXXFLAGS} -MM -MT "${subst .d,.o,$@} $@" -MF "$@" $<
 
ifneq (${MAKECMDGOALS},clean)
-include ${CDEF_WITH_PATH} ${CXXDEF_WITH_PATH}
endif
 
run:${TARGET}
	${TARGET_WITH_PATH}
 
debug:${TARGET}
	gdb ${TARGET_WITH_PATH}
 
.PHONY:check
check:
	@echo VPATH : ${VPATH}
	@echo CSRC_WITH_PATH : ${CSRC_WITH_PATH}
	@echo CSRC : ${CSRC}
	@echo COBJ_WITH_PATH : ${COBJ_WITH_PATH}
	@echo COBJ : ${COBJ}
	@echo CDEF : ${CDEF}
	@echo CXXSRC_WITH_PATH : ${CXXSRC_WITH_PATH}
	@echo CXXSRC : ${CXXSRC}
	@echo CXXOBJ_WITH_PATH : ${CXXOBJ_WITH_PATH}
	@echo CXXOBJ : ${CXXOBJ}
	@echo CXXDEF : ${CXXDEF}
 
.PHONY:clean
clean:
	-rm -f ${DIR_OBJ}*.o
	-rm -f ${DIR_OBJ}*.d
	-rm -f ${TARGET_WITH_PATH}

